package com.infomanage.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.infomanage.po.User;

public class LoginFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	private final static String[] eixt_url = { "login.jsp", "login_action.jsp"}; // 不用做权限判断的URL  

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession(true);
		String requestURI = req.getRequestURI();

		boolean canAccess = false;
		if (requestURI.indexOf(".jsp") >= 0)
			canAccess = false;

		for (int i = 0; i < eixt_url.length; i++) {
			if (requestURI.indexOf(eixt_url[i]) >= 0) {
				canAccess = true;
				break;
			}
		}
		if (canAccess) {
			chain.doFilter(request, response);
		} else {
			User user = (User) session.getAttribute(com.infomanage.util.Consts.LOGINED_USER);
			if (user == null) {
				res.sendRedirect(req.getContextPath() + "/login.jsp");
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	public void destroy() {

	}
}